package mdt.figure;

import org.tigris.gef.base.SelectionResize;
import org.tigris.gef.presentation.Fig;
import org.tigris.gef.presentation.Handle;

import java.util.List;

/**
 * Created by xiaobyu on 6/21/2016.
 */
public class SelectionNetworkDevice extends SelectionResize{
    /**
     * Construct a new SelectionResize for the given Fig
     *
     * @param f
     */
    public SelectionNetworkDevice(Fig f) {
        super(f);
    }

    public void dragHandle(int mX, int mY, int anX, int anY, Handle hand) {

        if (!getContent().isResizable()) {
            return;
        }

        final Fig contentFig = getContent();

        final List<Fig> figs = contentFig.getLayer().getContents();

        int minimumHeight = 0;
        for (Fig workOnFig : figs) {
            if (workOnFig instanceof FigNetworkDevice
                    && workOnFig.getMinimumSize().height > minimumHeight) {
                minimumHeight = workOnFig.getMinimumSize().height;
            }
        }

        int deltaY = mY - contentFig.getY();

        // vertical resizing
        switch (hand.index) {
            case Handle.NORTHWEST:
            case Handle.NORTH:
            case Handle.NORTHEAST:
                int newHeight = getContent().getHeight() - deltaY;
                if (newHeight < minimumHeight) {
                    newHeight = minimumHeight;
                    deltaY = contentFig.getHeight() - newHeight;
                }

                for (Fig workOnFig : figs) {
                    if (workOnFig instanceof FigNetworkDevice) {
                        workOnFig.setHeight(newHeight);
                        workOnFig.translate(0, deltaY);
                    }
                }

                // 3. Now reposition messages based on their original position
                for (Fig workOnFig : figs) {
                    if (workOnFig instanceof FigMessage || workOnFig instanceof FigShapedEdge) {
                        workOnFig.translate(0, deltaY);
                    }
                }
                break;
            case Handle.SOUTH:
            case Handle.SOUTHEAST:
            case Handle.SOUTHWEST:
                newHeight = deltaY;
                if (newHeight < minimumHeight) {
                    newHeight = minimumHeight;
                }
                for (Fig workOnFig : figs) {
                    if (workOnFig instanceof FigNetworkDevice) {
                        workOnFig.setHeight(newHeight);
                    }
                }
            default:
        }

        // horizontal resizing
        switch (hand.index) {
            case Handle.NORTHWEST:
            case Handle.SOUTHWEST:
                contentFig.setWidth(contentFig.getX() - mX + contentFig.getWidth());
                contentFig.setX(mX);
                break;
            case Handle.NORTHEAST:
            case Handle.SOUTHEAST:
                contentFig.setWidth(mX - contentFig.getX());
                break;

        }

    }
}
